<?php

namespace app\service;

use app\model\system\SysUser;
use App\Service\Logger;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use stdClass;
use support\Redis;

class JwtService
{
    public static $jwtSuffix = "sysJWTs:";

    public static function verifyToken($token): bool|stdClass
    {
        try {
            // 解码token
            $jwtUser = self::decodeToken($token);
            // 根据md5查找token_key是否存在
            if (Redis::exists(self::$jwtSuffix . $jwtUser->md5)) {
                return $jwtUser;
            } else {
                $sysUser = SysUser::where('username', $jwtUser->user)->find();
                if (!$sysUser) {
                    Logger::error("用户不存在");
                    return false;
                }
                if (md5($sysUser->username . $sysUser->password) == $jwtUser->md5) {
                    return $jwtUser;
                } else {
                    Logger::error("md5验证失败");
                    return false;
                }
            }
        } catch (\Exception $e) {
            Logger::error($e->getMessage());
            return false;
        }
    }

    public static function createToken($payload): string
    {
        $token = JWT::encode($payload, getenv('JWT_SECRET'), 'HS256');
        return $token;
    }

    public static function decodeToken($token): stdClass
    {
        $decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
        return $decoded;
    }

    /**
     * 保存token至到redis中，并设置过期时间
     */
    public static function saveToken(string $key, string $value): bool
    {
        return Redis::set(self::$jwtSuffix . $key, $value, expireTTL: config('JWT_EXPIRE', $_ENV['JWT_EXPIRE'])) ? true : false;
    }

    /**
     * 移除token
     */
    public static function removeToken($key): bool
    {
        return Redis::del(self::$jwtSuffix . $key) ? true : false;
    }
}
